import path from 'path';
import express from 'express';
import bodyParser from 'body-parser';
import apiRoute from './api/apiRoute';

const app = express();

// 获取端口号或者默认为8080
const port = process.argv.length > 2 ? parseInt(process.argv[2]) : 8080;
// 当前启动环境
const __DEV__ = process.env.NODE_ENV == 'development';
const __API__ = process.env.NODE_ENV == 'API';

// 静态目录
const staticResourceDir = `../assets/dist/${process.env.NODE_ENV}`;
const staticMapDir = `../assets/map`;

if (__DEV__) {
	// 启动webpack热加载
	const webpack = require('webpack');
	const config = require('../webpack.config.develop');
	const compiler = webpack(config);

	app.use(require('webpack-dev-middleware')(compiler, {
		noInfo: true,
		publicPath: config.output.publicPath
	}));

	app.use(require('webpack-hot-middleware')(compiler));
}

app.use(bodyParser.json()); // for parsing application/json
// app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
// app.use(multer()); // for parsing multipart/form-data

app.use('/api', apiRoute);

if (!__API__) {
	// 设置静态目录
	app.use('/static', express.static(path.join(__dirname, staticResourceDir)));
	app.use('/map', express.static(path.join(__dirname, staticMapDir)));

	// 返回承载页
	app.use('/app', (req, res, next) => {
		res.sendFile(path.join(__dirname, staticResourceDir, 'app.html'));
	});

	// 重定向到`/app`
	app.use('/', (req, res) => {
		res.status(302).redirect('/app');
	});
}

// 打开监听
app.listen(port, (err) => {
	if (err) return console.log(err);
	
	console.log(`listen http://localhost:${port}`);
});